package com.siboxuetang.need.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.siboxuetang.need.service.WechatService;
import com.siboxuetang.need.util.WebUtils;
import com.siboxuetang.need.vo.WechatConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * Create Time: 2018年04月25日 17:50
 *
 * @author fin
 */
@Service
public class WechatServiceImpl implements WechatService {

    @Autowired
    private WechatConfiguration wechatConfiguration;


    @Override
    public String getJsApiTicket() {
        String accessToken = this.getAccessToken().getString("access_token");
        return getJsApiTicket(accessToken).getString("ticket");
    }

    /**
     * 获取app id
     *
     * @return appid
     */
    @Override
    public String getAppId() {
        return wechatConfiguration.getAppid();
    }

    /**
     * 根据code临时凭证获取用户openid
     *
     * @param code
     * @return
     */
    @Override
    public String getUserOpenid(String code) {
        return getUserOpenidByCode(code).getString("openid");
    }

    private JSONObject getUserOpenidByCode(String code){
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"
                .replace("APPID", wechatConfiguration.getAppid())
                .replace("SECRET", wechatConfiguration.getAppSecret())
                .replace("CODE", code);

        return WebUtils.getRestTemplate().getForObject(url, JSONObject.class);
    }

    private JSONObject getJsApiTicket(String accessToken){
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=ACCESS_TOKEN&type=jsapi".replace("ACCESS_TOKEN", accessToken);
        return WebUtils.getRestTemplate().getForObject(url, JSONObject.class);
    }

    private JSONObject getAccessToken(){
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
        url = url.replace("APPID", wechatConfiguration.getAppid()).replace("APPSECRET", wechatConfiguration.getAppSecret());
        return  WebUtils.getRestTemplate().getForObject(url, JSONObject.class);
    }

}
